package action;

import inc.BeanUtil;
import inc.CommonFunction;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lottery.BetRecord;
import lottery.BetWay;
import lottery.Lottery;
import lottery.LotteryConfig;
import lottery.RewardTime;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.hibernate.Session;

import reflect.ReflectObject;
import code.lewdy.app.notice.Notice;
import code.lewdy.app.user.AccountRecord;
import code.lewdy.db.DataParams;
import code.lewdy.db.Database;
import code.lewdy.db.HibernatePage;
import code.lewdy.db.HibernateTemple;
import code.lewdy.db.JdbcUtil;
import code.lewdy.lottery.LotteryService;
import code.lewdy.reflect.MethodUtil;
import code.lewdy.time.TimeHelper;
import code.lewdy.util.DataType;
import code.lewdy.util.FormatUtil;
import code.lewdy.util.RandomUtil;
import code.lewdy.web.PassportUtil;
import code.lewdy.web.request.ExtRequest;
import code.lewdy.web.response.ExtResponse;

import com.lt.member.Member;
import com.lt.member.MemberStatistics;
import com.opensymphony.xwork2.ActionSupport;

import dao.HibernatePager;
import dao.HibernateSessionFactory;

public class DataAction extends ActionSupport implements ServletRequestAware,
		ServletResponseAware {
	private CommonFunction fun = new CommonFunction();
	private HttpServletRequest req;
	private HttpServletResponse resp;
    private ExtRequest extreq = null;
    private JdbcUtil jdbc = new JdbcUtil(Database.TYPE_SQLSERVER);
    
    private String classPath;
	private String className;
	private String condition;
	private int objId;
	private String lotteryName;
	private String betName; //投注方式
	private int ownerId;
	private String ext1; //扩展字段
	


	/**获取一个字符串
	 * @return
	 */
	public String getString(){
		String sql = ext1;
		String data = jdbc.getString(sql);
		//String data = (String)HibernateTemple.getUniqueResult(sql);
		ExtResponse.outString(resp, "<data>"+data+"</data>", "xml");
		return null;
	}
	
	public String getInt(){
		String sql = ext1;
		int data = jdbc.getInt(sql);
		ExtResponse.outString(resp, "<data>"+data+"</data>", "xml");
		return null;
	}
	
	public String getDouble(){
		String sql = ext1;
		double data = jdbc.getDouble(sql);
		data = FormatUtil.formatDecimal(data, 2);
		ExtResponse.outString(resp, "<data>"+data+"</data>", "xml");
		return null;
	}
	
    //query
    public String query(){
        int pageSize = extreq.getInt("pageSize")==0 ? 15 : extreq.getInt("pageSize");
        int page = extreq.getInt("page")==0 ? 1 : extreq.getInt("page");
        classPath = extreq.getString("classPath");
        condition = extreq.getString("condition")==null ? "" : extreq.getString("condition");
        HashMap map = null;
        Iterator keyIterator = null;
        String key = null;
        String results = fun.xmlAppend(null, null, "resp", null);
        //jdbc分页
       // List list = jdbc.list(classPath, condition, page, pageSize);
        List list = HibernatePage.listMSSQL(classPath, condition, page, pageSize);
        if (list.size() > 0) {
            results = fun.xmlAppend(results, "resp", "list", null);
        }
        results = fun.xmlAppend(results, "resp", "size", list.size());
        results = fun.xmlAppend(results, "resp", "page", page);
        //results = fun.xmlAppend(results, "resp", "total", pager.getSize());
        for (Object obj : list) {
            results = fun.xmlAppend(results, "list", "obj", null);
            map = ReflectObject.getFieldValues(obj, classPath);
            keyIterator = map.keySet().iterator();
            while (keyIterator.hasNext()) {
                key = (String) keyIterator.next();
                if(Notice.class.getName().equals(classPath) && key.equals("content")){
                	results = fun.xmlAppend(results, "obj", key, (""+map.get(key)).replace("<", "&lt;").replace(">", "&gt;"));
                }else if(Member.class.getName().equals(classPath) && key.equals("bankNo") && map.get(key)!= null){
                    results = fun.xmlAppend(results, "obj", "bankNo", "C"+(String)map.get(key));
                }else{
                	results = fun.xmlAppend(results, "obj", key, map.get(key));
                }
            }
            
        }
        fun.ajaxPrint(resp, "xml", null, results);
        //System.out.println("query:" + results);
        return null;
    }
   
	//delete
	public String delete() throws ClassNotFoundException{
        int results = 0;
        className = extreq.getString("className");
        classPath = extreq.getString("classPath");
        objId = extreq.getInt("objId");
        results = jdbc.delete(classPath, new Long(objId));
        System.out.println("delete()=>"+results);
		return null;
	}
	
	/**更新一个字段
	 * @return
	 */
	public String updateAField(){
		classPath = extreq.getString("classPath");
        objId = extreq.getInt("objId");
        String field = extreq.getString("field");
        String fieldValue = extreq.getString("fieldValue");
        jdbc.updateAField(classPath, "where id="+objId, field, fieldValue);
		return null;
	}
	
	// update
	public String update() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
        System.out.println("Update=>objId:" + objId);
        className = extreq.getString("className");
        objId = extreq.getInt("objId");
        String field = extreq.getString("field");
        String fieldValue = extreq.getString("fieldValue");
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		Object obj = null;
		try {
			obj = s.get(Class.forName(className), objId);
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		s.getTransaction().commit();
		if (obj != null) {
			if(field != null){
				//只更新一个属性
				Method ms[] = MethodUtil.getBeanMethods(className, "set");
				for(Method m : ms) {
					if(m.getName().toUpperCase().equals(("set"+field).toUpperCase())){
						String paramType = m.getParameterTypes()[0] + "";
						if(paramType.indexOf("int")>=0){
							m.invoke(obj, Integer.parseInt(fieldValue));
						}else{
							m.invoke(obj, fieldValue);
						}
					}
				}
			}else{
	            Object source = ActionHelper.getObject(req,
	                    className);
				BeanUtil.cloneProperties(source, obj);
			}
            s.beginTransaction();
			s.update(obj);
			s.getTransaction().commit();
		}
		s.close();
		return null;
	}

	// save
	public String save() throws UnsupportedEncodingException {
		String results = "";
		boolean error = false;
        className = extreq.getString("className");
        if(className == null){
        	className = extreq.getString("classPath");
        }
		Session s = HibernateSessionFactory.getSession();
		if (ClassName.CLASS_LOTTERY_CONFIG.equals(className)) {
			LotteryConfig lc = (LotteryConfig) ActionHelper.getObject(req,
					className);
			s.beginTransaction();
			s.save(lc);
			s.getTransaction().commit();
		}else if(BetRecord.class.getName().equals(className)){
			BetRecord br = (BetRecord) ActionHelper.getObject(req, className);
			Member user = (Member) HibernateTemple.load(Member.class, br.getOwnerId());
			 if(user.getAccountType() == 1){
				 ExtResponse.error(resp, "代理不能购买!", DataType.XML);
				return null;
			 }
			if(null == br.getNumberId() || "".equals(br.getNumberId())){
				results = "期号异常，投注失败！";
            	error = true;
			}
            //投注记录
			Date date = new Date();
			String currentNumberId = new LotteryService().getNewNumberId(br.getLotteryId());
			if(!currentNumberId.equals(br.getNumberId())){
				results = "期号不匹配，投注失败！";
            	error = true;
			}
			Lottery lottery = (Lottery) HibernateTemple.load(Lottery.class, br.getLotteryId());
			br.setLotteryName(lottery.getName());
			BetWay bet = (BetWay) HibernateTemple.load(BetWay.class, br.getBetId());
			String number = br.getNumber();
			String betName =bet.getName();
			br.setBetName(betName);
			if(betName.indexOf("单式")>0 && LotteryService.hasRepeat(number)){
				// 作弊
				ExtResponse.error(resp, "投注中含重复号码!", DataType.XML);
				return null;
			}
			br.setCreateDate(date);
            br.setLotteryName(lotteryName);
            br.setBetName(betName);
            br.setOrderId(RandomUtil.getRandomString(18));
            br.setIsPay(0);
            br.setIsWin(0);
            br.setIsCancel(0);
/*            s.beginTransaction();
            Member user = (Member) s.get(Member.class, br.getOwnerId());
            s.getTransaction().commit();*/
           
            double betAmount = br.getSingleAmount()*br.getCount();
            user.setBalance(user.getBalance()-betAmount);
            if(user.getBalance() >= 0 && !error){
            	//余额足够
            	br.setOwnerName(user.getUsername());
            	/*s.beginTransaction();
    			Long betId = Long.parseLong(s.save(br)+"");
    			s.update(user);
    			s.getTransaction().commit();*/
    			HibernateTemple.save(br);
    			HibernateTemple.update(user);
    			//账变记录
    			new AccountRecord().insert(user, br.getOrderId(), AccountRecord.GROUP_LOTTERY_BET, 
    					-betAmount, "投注消费");
            }else{
            	results = "抱歉！您的账户余额不足，投注失败！";
            	error = true;
            }
		}else if(ClassName.CLASS_MEMBER.equals(className)){
			//添加会员
			Member obj = (Member) ActionHelper.getObject(req, className);
			obj.setPassword(fun.encryptPassword(obj.getPassword()));
			s.beginTransaction();
			s.save(obj);
			s.getTransaction().commit();
		}else if(ClassName.CLASS_REWARD_TIME.equals(className)){
			RewardTime rt = new RewardTime();
	        rt.setBeginTime(TimeHelper.getSecondsByTime(extreq.getString("clock1")));
	        rt.setBetEndTimeSp(extreq.getInt("spbetEndTime")*60);
	        rt.setBetStartTimeSp(extreq.getInt("spbetBeginTime")*60);
	        rt.setEndTime(TimeHelper.getSecondsByTime(extreq.getString("clock2")));
	        rt.setFirstOpentTime(TimeHelper.getSecondsByTime(extreq.getString("firstBetTime")));
	        rt.setLotteryId(extreq.getInt("lotteryId"));
	        rt.setLotteryName(lotteryName);
	        rt.setOpenTimeSp(extreq.getInt("spaceTime")*60);
	        System.out.println("lotteryName:"+rt.getLotteryName());
	        s.beginTransaction();
	        s.save(rt);
	        s.getTransaction().commit();
		}else{
		    Object obj = ActionHelper.getObject(req,
                    className);
            s.beginTransaction();
            s.save(obj);
            s.getTransaction().commit();
        }
		if(s.isOpen())
			s.close();
		if(error){
			ExtResponse.error(resp, results, "xml");
		}else{
			ExtResponse.ok(resp, results, "xml");
		}
		return null;
	}

	// query
	public String getData() {
        int pageSize = extreq.getInt("pageSize")==0 ? 15 : extreq.getInt("pageSize");
        int page = extreq.getInt("page")==0 ? 1 : extreq.getInt("page");
        className = extreq.getString("className");
        condition = extreq.getString("condition")==null ? "" : extreq.getString("condition");
        //HibernatePager pager = new HibernatePager(className, condition, pageSize);
		HashMap map = null;
		Iterator keyIterator = null;
		String key = null;
		String results = fun.xmlAppend(null, null, "resp", null);
		List list = jdbc.list(classPath, condition, page, pageSize);
		if (list.size() > 0) {
			results = fun.xmlAppend(results, "resp", "list", null);
		}
		results = fun.xmlAppend(results, "resp", "size", list.size());
        results = fun.xmlAppend(results, "resp", "page", page);
       // results = fun.xmlAppend(results, "resp", "total", pager.getSize());
		for (Object obj : list) {
			results = fun.xmlAppend(results, "list", "obj", null);
			map = ReflectObject.getFieldValues(obj, className);
			keyIterator = map.keySet().iterator();
			while (keyIterator.hasNext()) {
				key = (String) keyIterator.next();
				results = fun.xmlAppend(results, "obj", key, map.get(key));
			}
		}
		fun.ajaxPrint(resp, "xml", null, results);
		System.out.println("getData:" + results);
		return null;
	}


	public void setServletResponse(HttpServletResponse resp) {
		// TODO Auto-generated method stub
		this.resp = resp;
	}

	public void setServletRequest(HttpServletRequest req) {
		// TODO Auto-generated method stub
		this.req = req;
        if(extreq == null)
            extreq = new ExtRequest(this.req);
	}

	public String getLotteryName() {
		return lotteryName;
	}

	public void setLotteryName(String lotteryName) {
		this.lotteryName = lotteryName;
	}

	public void setBetName(String betName) {
		this.betName = betName;
	}

	public String getBetName() {
		return betName;
	}

	public int getOwnerId() {
		return ownerId;
	}

	public void setOwnerId(int ownerId) {
		this.ownerId = ownerId;
	}
	
	public String getExt1() {
		return ext1;
	}

	public void setExt1(String ext1) {
		this.ext1 = ext1;
	}
	
}
